package com.yangzb.java.sample.xmly;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author yzb
 */
public class DownloadV2 {
    private int albumId;
    private String path;
    public static final String URL = "https://m.ximalaya.com/m-revision/common/album/queryAlbumTrackRecordsByPage?albumId={}&page={}&pageSize=10&asc=true&countKeys=play%2Ccomment&v={}";
//    public static final String URL_TRACK = "https://mpay.ximalaya.com/mobile/track/pay/{}/ts-{}?device=web&accoutInfo=&trackQualityLevel=0&isBackend=false";
    public static final String URL_TRACK = "https://mobile.ximalaya.com/mobile-playpage/track/v3/baseInfo/{}?device=web&trackQualityLevel=0&trackId={}";

    public static final Map<String, List<String>> HEADERS = new HashMap() {{
        put("User-Agent", ListUtil.of("Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1 Edg/99.0.4844.51"));
        put("Host", ListUtil.of("m.ximalaya.com"));
        put("cookie", ListUtil.of("_xmLog=h5&ba764b5b-dd94-4607-a3e2-35941cc626ae&2.4.7-alpha.3; x_xmly_traffic=utm_source%253A%2526utm_medium%253A%2526utm_campaign%253A%2526utm_content%253A%2526utm_term%253A%2526utm_from%253A; Hm_lvt_4a7d8ec50cfd6af753c4f8aee3425070=1646877059; Hm_lpvt_4a7d8ec50cfd6af753c4f8aee3425070=1646877059; xm-page-viewid=ximalaya-mobile; Hm_lvt_e2abff7f9ca8c2fa2da3ef27e36bbc27=1646813930,1646877079; Hm_lpvt_e2abff7f9ca8c2fa2da3ef27e36bbc27=1646877079"));
        put("referer", ListUtil.of("https://m.ximalaya.com/album/55718615?source=pc_jump"));
    }};

    public static final Map<String, List<String>> HEADERS_TRACK = new HashMap() {{
        put("User-Agent", ListUtil.of("Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1 Edg/104.0.5112.102"));
//        put("Host", ListUtil.of("m.ximalaya.com"));
        put("cookie", ListUtil.of("_xmLog=h5&ba764b5b-dd94-4607-a3e2-35941cc626ae&2.4.7-alpha.3; 1&remember_me=y; Hm_lvt_4a7d8ec50cfd6af753c4f8aee3425070=1673428856,1673505656; Hm_lpvt_4a7d8ec50cfd6af753c4f8aee3425070=1673505656; trackType=H5; x_xmly_traffic=utm_source%3A%26utm_medium%3A%26utm_campaign%3A%26utm_content%3A%26utm_term%3A%26utm_from%3A; impl=passport.ximalaya.com.m; fds_otp=7122554545039508001; 1&_token=47039528&3186EEC0340NBF774CEF8750F9AE74B35740CF80BB4138CB7EF6370A8D5C8ECAA125F0F05EDC153M56EE454FF96A0AE_; 1_l_flag=47039528&3186EEC0340NBF774CEF8750F9AE74B35740CF80BB4138CB7EF6370A8D5C8ECAA125F0F05EDC153M56EE454FF96A0AE__2023-01-1214:42:20; login_type=code_mobile; xm-page-viewid=ximalaya-mobile"));
//        put("referer", ListUtil.of("https://m.ximalaya.com/"));
    }};

    public DownloadV2(int albumId, String path) {
        this.albumId = albumId;
        this.path = path;
    }

    public void run(String replace) throws Exception {
        getTrackDetailInfos();
        int index = 1;
        for (Object o : allTrack) {
            JSON track = (JSON)o;
            String id = StrUtil.toString(track.getByPath("id"));
            String format = StrUtil.format(URL_TRACK, System.currentTimeMillis(), id);
            System.out.println(format);
            HttpRequest request = HttpUtil.createGet(format);
            request.header(HEADERS_TRACK);
            request.timeout(30000);
            HttpResponse response = request.execute();
            JSON parse = JSONUtil.parse(response.body());
            String url1 = StrUtil.toString(parse.getByPath("trackInfo.playUrlList[3].url"));
            String title = StrUtil.toString(parse.getByPath("trackInfo.title"));
            String url = UrlDecoder.decryptUrl(url1);
            System.out.println(id+":"+title+":"+url+">>"+index);
            TimeUnit.MILLISECONDS.sleep(200);
            HttpUtil.downloadFile(url,path+"/"+title.replaceAll(replace,"")+".mp3");
            index++;
        }
    }

    private JSONArray allTrack = JSONUtil.createArray();

    public void getTrackDetailInfos() throws Exception {
        int page = 1;
        int pageCount = Integer.MAX_VALUE;
        int totalCount = 0;
        while (page <= pageCount) {
            String url= StrUtil.format(URL, this.albumId, page, System.currentTimeMillis());
            HttpRequest request = HttpUtil.createGet(url);
            request.header(HEADERS);
            HttpResponse response = request.execute();
            JSON parse = JSONUtil.parse(response.body());
            if (page == 1) {
                totalCount = Integer.valueOf(StrUtil.toString(parse.getByPath("data.totalCount")));
//                totalCount = 10;
                pageCount = totalCount / 10;
                if (totalCount % 10 > 0 || totalCount == pageCount) {
                    pageCount += 1;
                }
            }
            JSONArray trackDetailInfos = JSONUtil.parseArray(parse.getByPath("data.trackDetailInfos"));
            allTrack.addAll(trackDetailInfos);
            System.out.println(StrUtil.format("总：{}个，页：{}=>{}",totalCount,pageCount,page));
            page ++;
            TimeUnit.MILLISECONDS.sleep(500);
        }
    }
}
